<?php
/**
 * AJAX角色管理接口
 * 处理用户角色的获取和保存操作
 */

// 错误报告设置 - 关闭显示错误，避免HTML输出
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

// 设置响应头 - 必须在任何输出之前
header('Content-Type: application/json; charset=utf-8');

// 开启会话
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 检查用户是否已登录
if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
    echo json_encode([
        'success' => false,
        'error' => '用户未登录'
    ]);
    exit();
}

// 数据库连接
try {
    if (!file_exists('database.php')) {
        throw new Exception("database.php文件不存在");
    }

    require_once 'database.php';

    if (!isset($conn) || !($conn instanceof mysqli)) {
        throw new Exception("数据库连接失败");
    }

    if (!$conn->ping()) {
        throw new Exception("数据库连接已断开");
    }

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => '数据库连接失败：' . $e->getMessage()
    ]);
    exit();
}

// 只处理POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        'success' => false,
        'error' => '只支持POST请求'
    ]);
    exit();
}

// 获取请求数据
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    echo json_encode([
        'success' => false,
        'error' => 'JSON解析错误: ' . json_last_error_msg()
    ]);
    exit();
}

// 验证必需参数
if (!isset($data['action']) || !isset($data['user_id'])) {
    echo json_encode([
        'success' => false,
        'error' => '缺少必需参数'
    ]);
    exit();
}

$action = $data['action'];
$user_id = strval($data['user_id']);
$current_user = strval($_SESSION['user_id']);

try {
    if ($action === 'get_roles') {
        // 获取用户当前角色
        $sql = "SELECT role FROM user_roles WHERE user_id = ? ORDER BY role";
        $stmt = $conn->prepare($sql);

        if (!$stmt) {
            throw new Exception("SQL准备失败: " . $conn->error);
        }

        $stmt->bind_param("s", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();

        $roles = [];
        while ($row = $result->fetch_assoc()) {
            $roles[] = $row['role'];
        }

        echo json_encode([
            'success' => true,
            'roles' => $roles,
            'message' => '角色获取成功'
        ]);

    } elseif ($action === 'save_roles') {
        // 保存用户角色
        if (!isset($data['roles']) || !is_array($data['roles'])) {
            throw new Exception("角色数据无效");
        }

        $new_roles = $data['roles'];

        // 开始事务
        $conn->begin_transaction();

        // 删除用户现有角色
        $delete_sql = "DELETE FROM user_roles WHERE user_id = ?";
        $delete_stmt = $conn->prepare($delete_sql);

        if (!$delete_stmt) {
            throw new Exception("删除SQL准备失败: " . $conn->error);
        }

        $delete_stmt->bind_param("s", $user_id);
        $delete_stmt->execute();

        // 插入新角色
        if (!empty($new_roles)) {
            $insert_sql = "INSERT INTO user_roles (user_id, role, assigned_by, assigned_at) VALUES (?, ?, ?, NOW())";
            $insert_stmt = $conn->prepare($insert_sql);

            if (!$insert_stmt) {
                throw new Exception("插入SQL准备失败: " . $conn->error);
            }

            foreach ($new_roles as $role) {
                $role = trim($role);
                if (!empty($role)) {
                    $insert_stmt->bind_param("sss", $user_id, $role, $current_user);
                    if (!$insert_stmt->execute()) {
                        throw new Exception("插入角色失败: " . $insert_stmt->error);
                    }
                }
            }
        }

        // 提交事务
        $conn->commit();

        // 返回更新后的角色列表
        $roles_sql = "SELECT role FROM user_roles WHERE user_id = ? ORDER BY role";
        $roles_stmt = $conn->prepare($roles_sql);
        $roles_stmt->bind_param("s", $user_id);
        $roles_stmt->execute();
        $roles_result = $roles_stmt->get_result();

        $updated_roles = [];
        while ($row = $roles_result->fetch_assoc()) {
            $updated_roles[] = $row['role'];
        }

        echo json_encode([
            'success' => true,
            'roles' => $updated_roles,
            'message' => '角色保存成功'
        ]);

    } else {
        throw new Exception("不支持的操作: " . $action);
    }

} catch (Exception $e) {
    // 回滚事务
    if (isset($conn) && $conn->inTransaction) {
        $conn->rollback();
    }

    // 记录错误日志
    error_log("AJAX角色管理错误: " . $e->getMessage());

    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

// 关闭数据库连接
if (isset($conn) && $conn instanceof mysqli) {
    $conn->close();
}
?>